package cn.com.eado.crm.v.fragment


import android.text.Editable
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import cn.com.eado.crm.R
import cn.com.eado.crm.app.KEY_USER_ID
import cn.com.eado.crm.app.MyApp
import cn.com.eado.crm.app.extenstion.toast
import cn.com.eado.crm.app.utils.SpUtil
import cn.com.eado.crm.m.db.MyDatabase
import cn.com.eado.crm.model.LoadStatus
import cn.com.eado.crm.v.adapter.RVCompanyAdapter
import cn.com.eado.crm.vm.CompanyViewModel
import cn.com.eado.preado.app.utils.autoCleared
import kotlinx.android.synthetic.main.fragment_company_search.*
import kotlin.concurrent.thread
import android.net.Uri
import android.content.Intent
import cn.com.eado.crm.databinding.FragmentInstituteSearchBinding
import cn.com.eado.crm.model.RetryCallback
import cn.com.eado.crm.v.adapter.RVInstituteAdapter
import cn.com.eado.crm.vm.InstituteViewModel


/**
 * A simple [Fragment] subclass.
 */
class InstituteSearchFragment : BaseBindingFragment<FragmentInstituteSearchBinding>(R.layout.fragment_institute_search) {

    private var vm by autoCleared<InstituteViewModel>()
    private var adapter by autoCleared<RVInstituteAdapter>()


    override fun onDestroy() {
        super.onDestroy()
        activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)  //恢复其它控件能操作
    }

    override fun initTheFragment() {
        initView()
        initViewModel()
        initBinding()
//        loadData()
    }

    private fun initView() {
        initTitleBar()
        initRecyclerView()
    }

    private fun initTitleBar() {
        titleBar8.setHint("设计院名称")
        titleBar8.searchCallback = { s ->
            loadData(s)
        }
    }

    private fun initRecyclerView() {
        recyclerView4.setHasFixedSize(true)
        recyclerView4.isNestedScrollingEnabled = false
        recyclerView4.layoutManager = LinearLayoutManager(activity)
        val adapter = RVInstituteAdapter({ view, pos, bean ->  //click
            thread {
//                val contact = MyDatabase.getInstance().contactDao().queryWithName(bean.InstituteName)
//                activity?.runOnUiThread {
//                    if(contact != null) showContact(contact)
//                    else activity?.toast("没有联系人!")
//                }
            }
        })
        recyclerView4.adapter = adapter
        this.adapter = adapter
    }

    private fun initViewModel(){
        vm = ViewModelProviders.of(this).get(InstituteViewModel::class.java)
        vm.searchInstitute.observe(this, Observer {
            if (it.status == LoadStatus.SUCCESS){
                Log.e("tag", "data size=${it.data?.rows?.size}")
                if (it.data?.rows?.isNotEmpty() == true){
                    this.adapter.refresh(it.data.rows)
                }else{
                    activity?.toast("没有数据")
                }
            }else if (it.status == LoadStatus.ERROR){
//                progressBar3.hide(activity)
            }
        })
    }

    private fun initBinding(){
        binding.lifecycleOwner = viewLifecycleOwner
        binding.result = vm.result
        binding.callback = object : RetryCallback {
            override fun retry() {
                vm.refresh()
            }
        }
    }

    private fun loadData(s: String){
//        mList.clear()
        vm.instituteName = s
        vm.userId = SpUtil.readInt(MyApp.instance, KEY_USER_ID, 0)
        vm.page2 = 1
        vm.setSearch(true)
    }



    /////////////////////////////////////////contact/////////////////////////////////////////////
//    private fun showContact(contact: Contact){
//        Log.e("tag", "........")
//        val name = "联系人"
//        val layout = initContact(contact)
//        AlertDialog.Builder(activity!!)
//            .setTitle(name)
//            .setView(layout)
////            .setPositiveButton("提交", null)//结合下面的dialog.getButton，保证点击确定不关闭dialog
//            .setNegativeButton("关闭"){ dialog, pos -> }
//            .show()
//    }

//    private fun initContact(contact: Contact): View {
//        val layout = View.inflate(activity, R.layout.contact, null)
//        val s = "    企业："
//        layout.findViewById<TextView>(R.id.tvName).text = s
//        val tvDepartment = layout.findViewById<TextView>(R.id.tvDepartment)
//        val tvPeople = layout.findViewById<TextView>(R.id.tvPeople)
//        val tvPosition = layout.findViewById<TextView>(R.id.tvPosition)
//        val tvPart = layout.findViewById<TextView>(R.id.tvPart)
//        val tvPhone = layout.findViewById<TextView>(R.id.tvPhone)
//        val tvCellPhone = layout.findViewById<TextView>(R.id.tvCellPhone)
//        val tvEmail = layout.findViewById<TextView>(R.id.tvEmail)
//        val tvRemark = layout.findViewById<TextView>(R.id.tvRemark)
//        //
//        tvDepartment.text = Editable.Factory.getInstance().newEditable(contact.name)
//        tvPeople.text = Editable.Factory.getInstance().newEditable(contact.people)
//        tvPosition.text = Editable.Factory.getInstance().newEditable(contact.position)
//        tvPart.text = Editable.Factory.getInstance().newEditable(contact.department)
//        tvPhone.text = Editable.Factory.getInstance().newEditable(contact.tel)
//        tvCellPhone.text = Editable.Factory.getInstance().newEditable(contact.cellPhone)
//        tvEmail.text = Editable.Factory.getInstance().newEditable(contact.email)
//        tvRemark.text = Editable.Factory.getInstance().newEditable(contact.remark)
//        //
//        tvPhone.setOnClickListener {
//            val intent = Intent(Intent.ACTION_DIAL)
//            intent.data = Uri.parse("tel:${tvPhone.text.toString()}")
//            startActivity(intent)
//        }
//        tvCellPhone.setOnClickListener {
//            val intent = Intent(Intent.ACTION_DIAL)
//            intent.data = Uri.parse("tel:${tvCellPhone.text.toString()}")
//            startActivity(intent)
//        }
//
//        return layout
//    }

}
